<template>
  <div class="app-container customer-div">
    <div style="margin-top: 40px">

      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
        <el-form-item label="发货单号：">
          <el-input v-model="listQuery.deliverSn"></el-input>
        </el-form-item>
        <el-form-item label="发货日期：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.deliverDate"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户编号：">
          <el-input v-model="listQuery.customerNumber"></el-input>
<!--          <el-autocomplete-->
<!--                  clearable-->
<!--                  class="inline-input"-->
<!--                  value-key="customerName"-->
<!--                  :fetch-suggestions="querySearch"-->
<!--                  v-model="listQuery.customerName"-->
<!--                  placeholder="请输入内容"-->
<!--                  @select="handleSelectCustomerName"-->
<!--                  :trigger-on-focus="false"-->
<!--          ></el-autocomplete>-->
        </el-form-item>
        <el-form-item label="业务员：">
          <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购员：">
          <el-select v-model="listQuery.purchaseUserId" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="牌号：" >
          <el-select v-model="listQuery.kingGoodsIds" filterable placeholder="请选择" clearable multiple="">
            <el-option
                    v-for="item in goodsList"
                    :key="item.kingId"
                    :label="item.goodsSn"
                    :value="item.kingId">
            </el-option>
          </el-select>
<!--          <el-input v-model="listQuery.goodsName"></el-input>-->
        </el-form-item>
<!--        <el-form-item label="牌号：">-->
<!--          <el-input v-model="listQuery.goodsSn"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="订单号：">
          <el-input v-model="listQuery.orderSn"></el-input>
        </el-form-item>
        <el-form-item label="费用类型：" >
          <el-select v-model="listQuery.freightType" filterable placeholder="请选择" clearable>
            <el-option key="sale" label="销售承担" value="sale"></el-option>
            <el-option key="purchase" label="采购承担" value="purchase"></el-option>
            <el-option key="logistics" label="运联承担" value="logistics"></el-option>
            <el-option key="customer" label="客户承担" value="customer"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否修改过采购底价：" label-width="150px">
          <el-select v-model="listQuery.hasChangePurchasePrice" filterable placeholder="请选择" clearable>
            <el-option :key="1" label="是" :value="1"></el-option>
            <el-option :key="0" label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
                  @click="handleSearchList()"
                  type="primary">
            查询
          </el-button>
          <el-button
                  v-if="saleImplementExport"
                  @click="downloadExcel"
                  type="primary">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--数据列表-->
    <div style="font-size:14px;line-height: 30px;padding:10px 0 ">
      发货数量：<span style="font-weight: bold;padding-right:10px">{{sendAllNum }}</span>金蝶毛利：<span style="font-weight: bold;padding-right:10px">{{allProfit }}</span>
    </div>
    <div class="table-container" style="margin-top:0">
      <el-table
              v-loading="listLoading"
              :data="tableData"
              border
              style="width: 100%;">

        <el-table-column  label="订单日期" width="100" align="center" prop="orderDate">
        </el-table-column>
        <el-table-column  label="订单号" width="150" align="center">
          <template slot-scope="scope">
              {{scope.row.orderSn}}
          </template>
        </el-table-column>
        <el-table-column  label="单据类型" width="100" align="center" prop="deliverType">
        </el-table-column>
        <el-table-column  label="采购评级" width="100" align="center" prop="customerLabel">
        </el-table-column>
        <el-table-column  label="发货日期" width="100" align="center" prop="shipTime">
        </el-table-column>
        <el-table-column  label="发货单号" width="140" align="center">
          <template slot-scope="scope">
              {{scope.row.deliverSn}}
          </template>
        </el-table-column>
        <el-table-column  label="业务员" width="100" align="center">
          <template slot-scope="scope">
            {{scope.row.userRealName}}
          </template>
        </el-table-column>
        <el-table-column
                label="客户编号"
                width="300">
          <template slot-scope="scope">
            <span>
                {{scope.row.customerNumber }}
              </span>
            <!--是否有权限-->
            <div v-if="scope.row.isShowCustomerName">{{scope.row.customerName}}</div>
          </template>
        </el-table-column>
        <el-table-column
                label="品名"
                align="center"
                width="150">
          <template slot-scope="scope">
            {{scope.row.goodsName}}
          </template>
        </el-table-column>
        <el-table-column
                label="牌号"
                align="center"
                width="150">
          <template slot-scope="scope">
            {{scope.row.goodsSn}}
          </template>
        </el-table-column>
        <el-table-column
                prop="goodsNum"
                label="合同数量"
                width="100"
                align="center">
        </el-table-column>
        <el-table-column
                label="合同单价"
                width="100"
                align="center">
          <template slot-scope="scope">
            {{scope.row.goodsPrice}}
          </template>
        </el-table-column>
        <el-table-column
                label="杂费(装卸费)"
                width="80"
                align="center">
          <template slot-scope="scope">
            {{scope.row.consultation}}
          </template>
        </el-table-column>
        <el-table-column
                label="合同行备注"
                width="400">
          <template slot-scope="scope">
            {{scope.row.remark}}
          </template>
        </el-table-column>
        <el-table-column
                label="本次发货数量"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.shipNum}}
          </template>
        </el-table-column>
        <el-table-column
                label="发货批号"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.batchNo}}
          </template>
        </el-table-column>
        <el-table-column
                label="实际运费"
                width="80"
                align="center">
          <template slot-scope="scope">
            {{scope.row.actualFreight}}
          </template>
        </el-table-column>

        <el-table-column
                align="center"
                label="费用类型"
                width="100">
          <template slot-scope="scope">
            {{scope.row.freightType}}
          </template>
        </el-table-column>

        <el-table-column
                label-class-name="bgth"
                label="采购预估底价"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.purchasePrice}}
          </template>
        </el-table-column>
        <el-table-column
                label-class-name="bgth"
                label="采购实际底价"
                width="140"
                align="center">
          <template slot-scope="scope">
            {{scope.row.purchaseActualPrice}}
          </template>
        </el-table-column>

        <el-table-column
                label="销售发货毛利"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.saleProfit}}
          </template>
        </el-table-column>

        <el-table-column
                label="实际发货仓库"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.shipWarehouse}}
          </template>
        </el-table-column>
        <el-table-column
                label="期望发货日期"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.expectSendDate}}
          </template>
        </el-table-column>
        <el-table-column
                label="预计发货日期"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.sendDate}}
          </template>
        </el-table-column>
        <el-table-column
                align="center"
                label="实际发货日期"
                width="120">
          <template slot-scope="scope">
            {{scope.row.shipDate}}
          </template>
        </el-table-column>

      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes,prev, pager, next,jumper"
              :current-page.sync="listQuery.pageNum"
              :page-size="listQuery.pageSize"
              :page-sizes="[10,15,20]"
              :total="count">
      </el-pagination>
    </div>

  </div>
</template>
<script>
  import {getCustomerOption,getOrderStatList,getOrderUsersList,getDeliverDetailList,exportDeliverDetailList,orderGoodsList} from '@/api/partner'
  import {formatDate} from '@/utils/date';
  import store from '@/store'
  import { mapGetters } from 'vuex'
  const defaultListQuery={
    pageNum: 1,
    pageSize: 10,
    goodsName: '',
    createDate:null,
    deliverDate:null,
    customerName:null,
    deliverSn:'',
    userId:'',
    isYunlianDeliver:'',
    orderSn:'',
    purchaseUserId:'',
    goodsSn:'',
    freightType:'',
    fromCompany:'',
    customerLabel:'',
    hasChangePurchasePrice:'',
    kingGoodsIds:[],
    type:'sale',
    customerNumber:''
  };
  export default {
    name: "index",
    data(){
      return {
        listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
        tableData: [],
        count: 0,
        listLoading: false,
        roles:store.getters.roles ? store.getters.roles : [],
        userOptionList:[],
        sendAllNum:'',
        allProfit:'',
        settleProfit:'',
        goodsList:[]
      }
    },
    computed: {
      ...mapGetters([
        'name',
        'mobile',
        'userId'
      ]),

      isCanSaleByDept(){
        if(this.roles.indexOf("saleDept") != -1){
          return true
        }else{
          return false
        }
      },
      isCanSaleByAll(){
        if(this.roles.indexOf("saleAll") != -1){
          return true
        }else{
          return false
        }
      },
      saleImplementExport(){
        if(this.roles.indexOf("saleImplementExport") != -1){
          return true
        }else{
          return false
        }
      },
    },
    created() {
      let now = new Date();
      let nowMonth = now.getMonth(); //当前月
      let nowYear = now.getFullYear(); //当前年
      //本月的开始时间
      let monthStartDate = new Date(nowYear, nowMonth, 1);
      //本月的结束时间
      let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
      let startDate = formatDate(monthStartDate, 'yyyy-MM-dd hh:mm:ss');
      let endDate = formatDate(monthEndDate, 'yyyy-MM-dd hh:mm:ss');
      this.listQuery.deliverDate = [startDate,endDate];


      if(this.$route.query.type){
        switch (this.$route.query.type) {
          case 'my':
            this.listQuery.tab = 'my';
            break;
          case 'myDay':
            this.listQuery.tab = 'my';
            this.listQuery.createdAt = [formatDate(new Date(), 'yyyy-MM-dd'),formatDate(new Date(), 'yyyy-MM-dd')];
            break;
          case 'dept':
            this.listQuery.tab = 'dept';
            break;
          case 'deptDay':
            this.listQuery.tab = 'dept';
            this.listQuery.createdAt = [formatDate(new Date(), 'yyyy-MM-dd'),formatDate(new Date(), 'yyyy-MM-dd')];
            break;
          case 'company':
            this.listQuery.tab = 'company';
            break;
          case 'companyDay':
            this.listQuery.tab = 'company';
            this.listQuery.createdAt = [formatDate(new Date(), 'yyyy-MM-dd'),formatDate(new Date(), 'yyyy-MM-dd')];
            break;
        }
      }
      this.getList();
      this.getUserOptionList();
      this.getOrderGoodsList();
    },
    filters: {
      formatCreateTime(time) {
        if(time){
          let date = new Date(time);
          return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
        }else{
          return '--'
        }
      },
    },
    methods:{
      getOrderGoodsList(){
        orderGoodsList().then((res)=>{
            this.goodsList = res.list
        })
      },
      //下载excle
      downloadExcel(){
        let params = JSON.parse(JSON.stringify(this.listQuery));
        params.source = 'saleAssistant';
        exportDeliverDetailList(params).then((res)=>{
          require.ensure([], () => {
            const { export_json_to_excel } = require('sheet/Export2Excel');
            const tHeader = res.title;
            const filterVal = res.columns;
            const list = res.list;
            const data = this.formatJson(filterVal, list);
            export_json_to_excel(tHeader, data, res.fileName);
          })
        })
      },

      //下载表格数据格式化
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      //查看发货单
      toDeliverDetail(deliverId){
        let routeData = this.$router.resolve({name:'deliverCon',query:{id:deliverId,type:'caiWu',}});
        window.open(routeData.href);
      },

      toOrderDetail(orderId){
        let routeData = this.$router.resolve({name:'purchaseDetail',query:{id:orderId,type:'see'}});
        window.open(routeData.href);
      },

      renderHeader (h) {
        return [h('div', {}, ['金蝶']),h('div', {}, ['成本单价'])]
      },

      renderHeader2 (h) {
        return [h('div', {}, ['成本单价']),h('div', {}, ['现金价'])]
      },
      renderHeader3 (h) {
        return [h('div', {}, ['采购底价']),h('div', {}, ['现金价'])]
      },
      renderHeader4 (h) {
        return [h('div', {}, ['合同单价']),h('div', {}, ['现金价'])]
      },

      //获取员工下拉选项
      getUserOptionList(){
        getOrderUsersList().then((res)=>{
          this.userOptionList = res;
        })
      },

      //选择员工名称
      handleSelectUserName(key,item){
        this.listQuery[key] = item.userId;
      },


      //客户名称输入匹配
      querySearch(queryString, cb){
        getCustomerOption({keywords:queryString}).then((res)=>{
          cb(res);
        })
      },


      //选择客户名称
      handleSelectCustomerName(item){
        this.listQuery.keywords = item.customerName
      },

      /**
       * 切换选择状态
       */
      handleSelect(key, keyPath){
        this.listQuery = JSON.parse(JSON.stringify(defaultListQuery)),
                this.listQuery.tab = key;
        this.handleSearchList();
      },
      handleSizeChange(val){
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val){
        this.listQuery.pageNum = val;
        this.getList();
      },

      handleSearchList(){
        this.listQuery.pageNum = 1;
        this.getList();
      },

      //获取发货明细列表
      getList() {
        this.listLoading = true;
        getDeliverDetailList(this.listQuery).then(response => {
          this.tableData = response.list;
          this.count = response.count;
          this.sendAllNum = response.sendAllNum;
          this.allProfit = response.allProfit;
          // this.settleProfit = response.settleProfit;
          this.listLoading = false;
        }).catch(()=>{
          this.listLoading = false;
        });
      },

    },
  }
</script>

<style scoped lang="scss">

  .upload-div{
    text-align: center;
    position:relative;
    #upload{

      opacity: 0;
      position: absolute;
      z-index: 1;
      width:154px;
      height:40px
    }
  }
</style>
